package com.example.ssmlab2.controller;

import com.example.ssmlab2.model.Book;
import com.example.ssmlab2.model.User;
import com.example.ssmlab2.service.BookService;
import com.example.ssmlab2.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.ref.ReferenceQueue;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    private final UserService userService;
    private final BookService bookService;


    public UserController(UserService userService, BookService bookService) {
        this.userService = userService;
        this.bookService = bookService;
    }

    @RequestMapping(value = "signUp", method = RequestMethod.POST)
    private String signUp(User user) {
        if (userService.query("queryUserByUsername", user.getUsername()) != null) {
            request.setAttribute("message", "您注册的用户名已存在，请重新输入！");
            return "/sign_up.jsp";
        }
        userService.create(user);
        request.setAttribute("message", "您的ID是：" + user.getId());
        return "/index.jsp";
    }

    @RequestMapping(value = "signIn", method = RequestMethod.POST)
    private String signIn(User user) {
        int id = user.getId();
        String password = user.getPassword();
        user = userService.queryById(id);
        String dbPassword = user.getPassword();
        if (dbPassword == null) {
            request.setAttribute("message", "您的ID 或 密码输入有误请重新输入！");
            return "/index.jsp";
        }
        if (password.equals(dbPassword)) {
            session.setAttribute("user", user);
            List<Book> books = bookService.queryAll();
            session.setAttribute("books", books);
            System.out.println(books);
            return "redirect:/user/index.jsp";
        } else {
            request.setAttribute("message", "您的ID 或 密码输入有误请重新输入！");
            return "/index.jsp";
        }
    }

    @RequestMapping(value = "signOut", method = RequestMethod.GET)
    private String signOut() {
        session.invalidate();
        return "redirect:/index.jsp";
    }

}
